﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cn.Edwon.Web.Support;
using Cn.Cellula.Module.Stat.Model;
using Cn.Edwon.Biz;
using Cn.Edwon.Spring;
using Cn.Edwon.Data;
using System.Text;
using Cn.Cellula.Module.Stat.FusionCharts;
using Cn.Edwon.Util;
using System.Data;
using Cn.Cellula.Client;
using Cn.Cellula.Model.Content;
using Cn.Cellula.Biz.Port;
using Cn.Cellula.Model.Security;

namespace Cn.Cellula.MiniTopSite.Ws {
    public partial class _Stat : PageSupport {
        IBiz biz = BizFactory.Get<IBiz>();
        String _Action = "";
        String _StatKey = "";
        protected void Page_Load(object sender, EventArgs e) {
            _Action = Request.QueryString["act"];
            _StatKey = Request.QueryString["stat"];
            if (_Action == "form") {
                ResponseOut(BuildForm(_StatKey));
            } else if(_Action=="stat"){
                ResponseOut(this.BuildStatData(_StatKey));
            } else {
                log.Error("Params lost in _Stat Webservice");
                ResponseOut("[]/*Params lost*/");
            }
        }
        private void ResponseOut(String Content) {
            Response.Clear();
            Response.Write(Content);
            Response.End();
        }

        private String BuildErrorMsg(String rMsg) {
            String msg = "{";
            msg += "\"ex\":\"" + rMsg.Replace("\"","`") + "\"";
            msg += "}";
            return msg;
        }
        /// <summary>
        /// 构造参数集合
        /// </summary>
        /// <param name="s"></param>
        /// <param name="pl"></param>
        /// <param name="se"></param>
        /// <returns></returns>
        private IList<CallingParameter> BuildParam(ModVStatEO s, IList<ModVStatParamEO> pl, ModVStatSeriesEO se) {
            IList<CallingParameter> _params = new List<CallingParameter>();
            if (!String.IsNullOrEmpty(se.SeriesParam)) {
                _params.Add(new CallingParameter(se.SeriesParam, se.SeriesValue, false));
            }
            foreach (ModVStatParamEO p in pl) {
                _params.Add(new CallingParameter(p.ParamName, Request.QueryString[p.FormFieldKey], (p.DataType=="number")));
            }
            return _params;
        }

        /// <summary>
        /// 构造统计数据，包括图表的xml数据和列表的数据
        /// </summary>
        /// <param name="rStatKey"></param>
        /// <returns></returns>
        private String BuildStatData(String rStatKey) {
            StringBuilder sb = new StringBuilder();
            ModVStatEO eo = biz.Load<ModVStatEO>(rStatKey);
            IList<ModVStatSeriesEO> seriesList = biz.Find<ModVStatSeriesEO>("from ModVStatSeriesEO eo where eo.StatKey='" + eo.StatKey + "' order by eo.OrderNumber desc");
            IList<ModVStatParamEO> paramsList = biz.Find<ModVStatParamEO>("from ModVStatParamEO eo where eo.StatKey='" + eo.StatKey + "' order by eo.OrderNumber desc");
            IList<ModVStatColumnsEO> columnsList = biz.Find<ModVStatColumnsEO>("from ModVStatColumnsEO eo where eo.StatKey='" + eo.StatKey + "' order by eo.OrderNumber desc");
            String ChartDataXml = "";
            StringBuilder sbGrid = new StringBuilder();
            int gridIdx = 0;
            sbGrid.Append("[");
            if (seriesList != null && seriesList.Count > 0) {
                IList<DataSet> data = new List<DataSet>();
                foreach (ModVStatSeriesEO se in seriesList) {
                    DataSet ds;
                    try {
                        ds = biz.ADOExcuteProc(eo.SrcName, BuildParam(eo,paramsList,se));
                        data.Add(ds);
                    } catch (Exception ex) {
                        log.Error("读取" + se.SeriesTitle + "数据时出现异常");
                        log.Error(ex.Message);
                        log.Error(ex.StackTrace);
                        return BuildErrorMsg("读取[" + se.SeriesTitle + "]数据时出现异常:$n" + ex.Message);
                    }
                    try {
                        if (gridIdx > 0)
                            sb.Append(",");
                        sbGrid.Append(BuildGridData(eo, se, columnsList, ds));
                        gridIdx++;
                    } catch (Exception ex) {
                        log.Error("构造" + se.SeriesTitle + "表单数据时出现异常");
                        log.Error(ex.Message);
                        return BuildErrorMsg("构造[" + se.SeriesTitle + "]表单数据时出现异常:$n" + ex.Message);
                    }
                }
                try {
                    FChartBuilder fcb = new FChartBuilder(eo, seriesList);
                    ChartDataXml = fcb.BuildChartXmlContent(data);
                } catch (Exception ex) {
                    log.Error("构造XmlData数据时出现异常");
                    log.Error(ex.Message);
                    return BuildErrorMsg("构造XmlData数据时出现异常:$n" + ex.Message);
                }
             }
            sbGrid.Append("]");
            sb.Append("{");
            sb.Append("\"xmldata\":\"" + ChartDataXml + "\"");
            sb.Append(",\"griddata\":" + sbGrid.ToString() + "");
            sb.Append("}");
            return sb.ToString();
        }
        /// <summary>
        /// 修正Json数据
        /// </summary>
        /// <param name="rContent"></param>
        /// <returns></returns>
        private String FixJsonData(String rContent) {
            rContent = rContent.Replace("\"", "\\\"");
            //rContent = rContent.Replace("<", "&lt;");
            //rContent = rContent.Replace(">", "&gt;");
            return rContent;
        }
        /// <summary>
        /// 构造列表数据
        /// </summary>
        /// <param name="stat"></param>
        /// <param name="series"></param>
        /// <param name="columns"></param>
        /// <param name="ds"></param>
        /// <returns></returns>
        private String BuildGridData(ModVStatEO stat, ModVStatSeriesEO series, IList<ModVStatColumnsEO> columns, DataSet ds) {
            if (ds == null) {
                log.Error("No Dataset Data for GridTable");
                return "[]/*No Dataset Data for GridTable*/";
            }
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("\"title\":\"" + series.SeriesTitle + "\"");
            //header
            sb.Append(",\"header\":[");
            sb.Append("{\"caption\":\"" + stat.DataTextCaption + "\",\"sum\":0}");
            sb.Append(",{\"caption\":\"" + stat.DataValueCaption + "\",\"sum\":1}");
            foreach (ModVStatColumnsEO col in columns) {
                sb.Append(",{\"caption\":\"" + col.ColumnTitle + "\"");
                if(col.IsCountColumn==1)
                    sb.Append(",\"sum\":0");
                else
                    sb.Append(",\"sum\":1");
                sb.Append("}");
            }
            sb.Append("]");

            //body
            sb.Append(",\"body\":[");
            int idx = 1;
            foreach (DataRowView row in ds.Tables[0].DefaultView) {
                if (idx > 1)
                    sb.Append(",");
                sb.Append("[");
                if (String.IsNullOrEmpty(row[stat.DataTextField].ToString())) {
                    sb.Append("\"" + TxtDef.OTHER + "\"");
                } else {
                    sb.Append("\"" + FixJsonData(row[stat.DataTextField].ToString()) + "\"");
                }
                if (String.IsNullOrEmpty(row[stat.DataValueField].ToString())) {
                    sb.Append(",\"--\"");
                } else {
                    sb.Append(",\"" + FixJsonData(row[stat.DataValueField].ToString()) + "\"");
                }
                foreach (ModVStatColumnsEO col in columns) {
                    if (row[col.ColumnField] == null) {
                        sb.Append(",\"Error\"");
                    } else if (String.IsNullOrEmpty(row[col.ColumnField].ToString())) {
                        sb.Append(",\"--\"");
                    } else {
                        sb.Append(",\"" + FixJsonData(row[col.ColumnField].ToString()) + "\"");
                    }
                } 
                sb.Append("]");
                idx++;
            }
            sb.Append("]");
            sb.Append("}");
            return sb.ToString();
        }
        /// <summary>
        /// 构造查询的Form
        /// </summary>
        /// <param name="rStatKey"></param>
        /// <returns></returns>
        private String BuildForm(String rStatKey) {
            IList<ModVStatParamEO> paramList = biz.Find<ModVStatParamEO>("from ModVStatParamEO eo where eo.StatKey='" + rStatKey + "' order by eo.OrderNumber desc");
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            for(int i=0;i<paramList.Count;i++){
                ModVStatParamEO p = paramList[i];
                if (i > 0)
                    sb.Append(",");
                sb.Append("{");
                sb.Append("\"key\":\""+p.FormFieldKey+"\"");
                sb.Append(",\"label\":\"" + p.ParamLabel + "\"");
                if (p.ParamType == (Int32)FormFieldType.Input) {
                    sb.Append(",\"def\":\"" + p.DefaultValue + "\"");
                    sb.Append(",\"type\":\"input\"");
                } else if (p.ParamType == (Int32)FormFieldType.DateTime) {
                    String def = (String.IsNullOrEmpty(p.DefaultValue)) ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : p.DefaultValue;
                    sb.Append(",\"def\":\"" + def + "\"");
                    sb.Append(",\"type\":\"datetime\"");
                } else if (p.ParamType == (Int32)FormFieldType.Date) {
                    String def = (String.IsNullOrEmpty(p.DefaultValue)) ? DateTime.Now.ToString("yyyy-MM-dd") : p.DefaultValue;
                    sb.Append(",\"def\":\"" + def + "\"");
                    sb.Append(",\"type\":\"date\"");
                } else if (p.ParamType == (Int32)FormFieldType.Month) {
                    String def = (String.IsNullOrEmpty(p.DefaultValue)) ? DateTime.Now.Month.ToString() : p.DefaultValue;
                    sb.Append(",\"def\":\"" + def + "\"");
                    sb.Append(",\"type\":\"month\"");
                } else if (p.ParamType == (Int32)FormFieldType.Week) {
                    Int32 totalWeeks = DateUtil.TotalWeeks(DateTime.Now);
                    Int32 year = DateTime.Now.Year;
                    String def = (String.IsNullOrEmpty(p.DefaultValue)) ? DateUtil.WeekOfYear(DateTime.Now).ToString() : p.DefaultValue;
                    sb.Append(",\"def\":\"" + def + "\"");
                    sb.Append(",\"type\":\"week\"");
                    sb.Append(",\"totalWeeks\":" + totalWeeks);
                } else if (p.ParamType == (Int32)FormFieldType.Year) {
                    String def = (String.IsNullOrEmpty(p.DefaultValue)) ? DateTime.Now.Year.ToString() : p.DefaultValue;
                    sb.Append(",\"def\":\"" + def + "\"");
                    sb.Append(",\"type\":\"year\"");
                } else if (p.ParamType == (Int32)FormFieldType.Item) {
                    IList<VItemListEO> items = BizFactory.Get<IItemBiz>().LoadItemByCategory(p.ItemCategoryKey, this.OwnerKey, this.Power);
                    String def = (items != null && items.Count > 0) ? items[0].ItemKey : "";
                    String defName = (items != null && items.Count > 0) ? items[0].ItemName : "";
                    sb.Append(",\"def\":\"" + def + "\"");
                    sb.Append(",\"defName\":\"" + defName + "\"");
                    sb.Append(",\"type\":\"item\"");
                    sb.Append(",\"catKey\":\"" + p.ItemCategoryKey + "\"");
                } else if (p.ParamType == (Int32)FormFieldType.User) {
                    IList<VSysUserEO> items = BizFactory.Get<IUserBiz>().LoadAllUsers();
                    String def = (items != null && items.Count > 0) ? items[0].UserKey : "";
                    String defName = (items != null && items.Count > 0) ? items[0].UserName : "";
                    sb.Append(",\"def\":\"" + def + "\"");
                    sb.Append(",\"defName\":\"" + defName + "\"");
                    sb.Append(",\"type\":\"user\"");
                } else if (p.ParamType == (Int32)FormFieldType.Dept) {
                    IList<TSysDeptEO> items = BizFactory.Get<IDeptBiz>().LoadAll<TSysDeptEO>();
                    String def = (items != null && items.Count > 0) ? items[0].DeptKey : "";
                    String defName = (items != null && items.Count > 0) ? items[0].DeptName : "";
                    sb.Append(",\"def\":\"" + def + "\"");
                    sb.Append(",\"defName\":\"" + defName + "\"");
                    sb.Append(",\"type\":\"dept\"");
                }
                sb.Append("}");
            }
            sb.Append("]");
            return sb.ToString();
        }
    }
}